package com.tamo.ppresta.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author yeyang
 * @name ppresta
 * @class name：com.tamo.ppresta.util
 * @class describe
 * @time 2022/12/23 15:35
 * @change
 * @chang time
 * @class describe
 */
public class AESUtils {

    /**
     * 获取随机password前19位
     *
     * @param privateKey
     * @return
     */
    public static String getPrivateKeyFront(String privateKey) {
        return privateKey.substring(0, 19);
    }

    /**
     * 获取随机password后5位
     *
     * @param privateKey
     * @return
     */
    public static String getPrivateKeyBehind(String privateKey) {
        return privateKey.substring(19, 24);
    }

    /**
     * 获取随机数字或者大小写字母
     *
     * @param length
     * @return
     */
    public static String getPrivateKey(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字

            if ("char".equalsIgnoreCase(charOrNum)) // 字符串
            {
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) // 数字
            {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 获取随机字符串
     *
     * @param lenght
     * @return
     */
    public static String getRandomStr(int lenght) {
        char[] mapTable = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
                'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                'w', 'x', 'y', 'z'};
        // 取随机产生的随机码
        String strEnsure = "";
        // j代表j位随机码
        for (int i = 0; i < lenght; ++i) {
            strEnsure += mapTable[(int) (mapTable.length * Math.random())];
        }
        return strEnsure;
    }

    /**
     * AES 加密
     *
     * @param content  内容明文
     * @param password 秘钥
     * @param viparr   偏移量（加密向量）
     * @return
     */
    public static String aesEncrypt(String content, String password, String viparr) {
        try {
            System.out.println("加密content=" + content);
            System.out.println("加密password=" + password);
            IvParameterSpec zeroIv = new IvParameterSpec(viparr.getBytes());
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
            byte[] encryptedData = cipher.doFinal(content.getBytes("utf-8"));
            System.out.println("加密encryptedData=" + Base64Utils.encode(encryptedData));
            return Base64Utils.encode(encryptedData);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES 解密
     *
     * @param content  内容密文
     * @param password 秘钥
     * @param viparr   偏移量（加密向量）
     * @return
     */
    public static String aesDecrypt(String content, String password, String viparr) {
        try {
            System.out.println("解密content=" + content);
            System.out.println("解密password=" + password);
            byte[] byteMi = Base64Utils.decode(content);
            IvParameterSpec zeroIv = new IvParameterSpec(viparr.getBytes());
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
            byte[] decryptedData = cipher.doFinal(byteMi);
            System.out.println("解密realBody=" + new String(decryptedData, "utf-8"));
            return new String(decryptedData, "utf-8");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return null;
    }
} 